<template>
  <div class="page-container">
    <div class="descriptions">
      <a-space direction="vertical" style="display: block">
        <a-row>
          <a-col :span="24">
            <div class="descriptions-title">模板信息</div>
          </a-col>
          <a-col :span="12">
            <div class="descriptions-item">
              <div class="label">模板名称</div>
              <div>{{ form.typeName }}</div>
            </div>
          </a-col>
          <a-col :span="12">
            <div class="descriptions-item">
              <div class="label">模板状态</div>
              <div>{{ form.statusName }}</div>
            </div>
          </a-col>
          <a-col :span="24">
            <div class="descriptions-item">
              <div class="label">模板说明</div>
              <div>
                <div v-for="item in form.memo" :key="item">{{ item }}</div>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-space>
    </div>
    <a-divider />
    <page-form :model="form" ref="formRef" layout="vertical">
      <card title="推送规则" :showDivider="false">
        <page-form-item
          label="通知方式"
          field="sendTypeList"
          :rules="[{ type: 'array', message: '请选择通知方式', required: true }]"
          required
        >
          <a-checkbox-group v-model="form.sendTypeList" :disabled="form.type === 9 || form.type === 10 || form.type === 31">
            <a-checkbox v-for="item in dict.sendTypeEnum" :key="item.value" :value="item.value">{{ item.label }}</a-checkbox>
          </a-checkbox-group>
        </page-form-item>
        <div class="message-center-box" v-if="form.sendTypeList?.includes(1) || form.sendTypeList?.includes(2)">
          <template v-if="form.sendTypeList.includes(1)">
            <div class="message-center-title">消息中心</div>
            <div class="message-center-item app">
              <page-form-item label="是否在手机端推送消息">
                <a-radio-group v-model="form.needAppPush" :disabled="form.type === 9 || form.type === 10">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </page-form-item>
              <page-form-item label="推送位置" v-show="form.needAppPush === 1">
                <template #label-extra> <a-link @click="() => onClickView('app')">【查看样式】</a-link> </template>
                <a-checkbox-group v-model="form.appPositionList" :disabled="form.type === 9 || form.type === 10 || form.needAppPush === 1">
                  <a-checkbox v-for="item in dict.appPositionEnum" :key="item.value" :value="item.value">{{ item.label }}</a-checkbox>
                </a-checkbox-group>
              </page-form-item>
            </div>
            <div class="message-center-item web">
              <page-form-item label="是否在电脑端推送消息">
                <a-radio-group v-model="form.needPcPush" :disabled="form.type === 9 || form.type === 10">
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </page-form-item>
              <page-form-item label="推送位置" v-show="form.needPcPush === 1">
                <template #label-extra> <a-link @click="() => onClickView('pc')">【查看样式】</a-link> </template>
                <a-checkbox-group v-model="form.pcPositionList" :disabled="form.type === 9 || form.type === 10 || form.needPcPush === 1">
                  <a-checkbox v-for="item in dict.pcPositionEnum" :key="item.value" :value="item.value">{{ item.label }}</a-checkbox>
                </a-checkbox-group>
              </page-form-item>
            </div>
          </template>
          <template v-if="form.sendTypeList.includes(2)">
            <div class="message-center-title">短信</div>
            <div class="message-center-item text">
              <div class="text-title">短信内容</div>
              <div class="text-content">{{ form.smsTemplate || '-' }}</div>
            </div>
          </template>
        </div>
        <div class="message-center-box">
          <div class="text">
            <div class="text-title">推送时间</div>
            <span class="text-content">{{ form.sendTimeDesc || '-' }}</span>
            <a-button
              type="outline"
              v-if="
                form.type !== 1 &&
                form.type !== 2 &&
                form.type !== 10 &&
                form.type !== 21 &&
                form.type !== 22 &&
                form.type !== 23 &&
                form.type !== 25 &&
                form.type !== 26 &&
                form.type !== 27 &&
                form.type !== 28 &&
                form.type !== 29 &&
                form.type !== 30 &&
                form.type !== 31 &&
                form.type !== 33 &&
                form.type !== 34 &&
                form.type !== 35 &&
                form.type !== 36 &&
                form.type !== 37 &&
                form.type !== 38
              "
              size="mini"
              @click="onClickTime"
            >
              {{ settingButton }}
            </a-button>
          </div>
        </div>
        <div class="message-center-box" v-if="form.type !== 31">
          <div class="text">
            <div class="text-title">推送内容</div>
            <div class="text-content">{{ form.pushContent || '-' }}</div>
          </div>
        </div>
        <div class="message-center-box">
          <div class="text">
            <page-form-item label="选择推送的人员" size="2/3">
              <a-radio-group
                v-model="form.sendTargetType"
                :disabled="
                  form.type === 2 ||
                  form.type === 9 ||
                  form.type === 10 ||
                  form.type === 20 ||
                  form.type === 21 ||
                  form.type === 22 ||
                  form.type === 23 ||
                  form.type === 24 ||
                  form.type === 25 ||
                  form.type === 26 ||
                  form.type === 27 ||
                  form.type === 28 ||
                  form.type === 29 ||
                  form.type === 30 ||
                  form.type === 33
                "
                @change="onChange"
              >
                <a-radio v-for="item in form.sendTargetTypeSelectList" :key="item.value" :value="+item.value">{{ item.name }}</a-radio>
              </a-radio-group>
            </page-form-item>
            <template v-if="sendTargetSource == 1">
              <a-select
                style="width: 25%; margin-top: 5px"
                v-model="sendTargetObj[sendTargetSource]"
                multiple
                allow-clear
                placeholder="请选择"
              >
                <a-option v-for="item in allRoleList" :key="item.id" :value="item.id + ''">
                  {{ item.role }}
                </a-option>
              </a-select>
            </template>
            <template v-if="sendTargetSource == 2">
              <a-select
                style="width: 25%; margin-top: 5px"
                v-model="sendTargetObj[sendTargetSource]"
                multiple
                allow-clear
                placeholder="请选择"
              >
                <a-option v-for="item in allPostList" :key="item.value" :value="item.value">
                  {{ item.name }}
                </a-option>
              </a-select>
            </template>
            <template v-if="sendTargetSource == 3">
              <a-alert style="margin-bottom: 10px">
                <template #icon>
                  <icon-exclamation-circle />
                </template>
                选择员工发送时，员工不受门店限制，所有门店下符合的，消息都发送。
              </a-alert>
              <fast-transfer
                style="width: 60%"
                v-model="sendTargetObj[sendTargetSource]"
                :selectedList="selectedList"
                :data-source="getRoleData"
              />
            </template>
          </div>
        </div>
      </card>
    </page-form>
    <page-form-footer :ok-loading="okLoading" @ok="submitFn" />

    <notice-dialog
      :layout="layout"
      :title="noticeDialogTitle"
      v-model="visible"
      :data="noticeDialogData"
      @ok="onOkOrderTime"
      @close="onCloseOrderTime"
    >
      <template #append>
        <a-select v-model="form.sendConfigJson.dateType">
          <a-option :value="1">小时</a-option>
          <a-option :value="2">天</a-option>
        </a-select>
      </template>
    </notice-dialog>

    <view-dialog v-model="viewVisible" :type="viewType" />
  </div>
</template>

<script setup lang="ts" name="MessageTemplateForm">
  import noticeDialog from '../dialog/notice-dialog.vue'
  import viewDialog from '../dialog/view-dialog.vue'

  import { ref, onMounted } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import { getStaff, getBusinessMessageDetail, saveBusinessMessage, changePushTime } from '@/api/business/message'
  import { getEpList } from '@/api/merchant/role'
  import { getSysParams } from '@/api/common'

  import { useRoute } from 'vue-router'
  import { Message } from '@arco-design/web-vue'
  import useNavigate from '@/hooks/useNavigate'
  import { cloneDeep } from 'lodash-es'

  const { navigateBack } = useNavigate()
  const dict = usePageDict('messagePageData')
  console.log(dict, 'dict')
  const route = useRoute()
  const okLoading = ref(false)
  const visible = ref(false)
  const viewVisible = ref(false)
  const viewType = ref('pc')
  const settingButton = ref('设置通知时间')

  const form = ref<any>({
    sendTypeList: [],
    sendConfigJson: {},
  })
  const formRef = ref()

  /**
   * 相关参数参照及编辑时可修改的功能
   * 1. 新订单通知：通知方式及推送人员
   * 2. OTA订单同步成功/失败：通知方式
   * 3. 待排车通知：通知方式、推送时间及推送人员
   * 4. 即将交车通知：3
   * 5. 即将还车通知：3
   * 6. 逾期未交通知：3
   * 7. 逾期未还通知：3
   * 8. 电子合同未签署：3
   * 9. 账户余额不足通知：推送时间
   * 10. 充值到账通知：-
   * 11. 车辆油电量异常：3
   * 12. 车辆里程异常：3
   * 13. 交强险即将到期通知：3
   * 14. 商业险即将到期通知：3
   * 15. 即将保养通知：3
   * 16. 即将年检通知：3
   * 17. 待维修车辆通知：3
   * 18. 待处理违章通知：3
   * 19. 车辆冲突：3
   * 20. 待指派负责人：通知方式、推送时间
   * 21. 待接单：2
   * 22. 待审核改派：2
   * 23. 申请改派结果通知：2
   * 24. 待处理工单：20
   * 25. 负责人拒绝：2
   * 26. 审批待处理通知：2
   * 27. 审批处理结果通知：2
   * 28. 支出单待付款通知：2
   * 29. 支出单完成付款通知：2
   * 30. 支出单完成付款通知：2
   * 31. 未处理违章通知-承租人：10
   * 33. 车型价格反写结果：-
   * 34. 三方账单支付结果通知：1
   */

  const layout = ref<'horizontal' | 'vertical'>('vertical')
  const noticeDialogTitle = ref('设置间隔时间')
  const noticeDialogData = ref()

  const onClickTime = () => {
    visible.value = true
    if (form.value.type === 3) {
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'order',
          children: [
            {
              first: '短租：预计交车前',
              value: form.value.sendConfigJson.soTimeDelta,
              unit: '分钟',
              precision: 0,
              second: '未排车则通知',
            },
          ],
        },
        {
          type: 'select',
          ident: 'order',
          children: [
            {
              first: '长租：每天',
              value: form.value.sendConfigJson.loDayHour,
              second: '通知当天交车但未排车的订单',
            },
          ],
        },
      ]
    }
    if (form.value.type === 4) {
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'order',
          children: [
            {
              first: '短租：交车时间前',
              value: form.value.sendConfigJson.soTimeDelta,
              unit: '分钟',
              precision: 0,
              second: '还未交车则通知',
            },
          ],
        },
        {
          type: 'select',
          ident: 'order',
          children: [
            {
              first: '长租：每天',
              value: form.value.sendConfigJson.loDayHour,
              second: '通知当天交车但未交的订单',
            },
          ],
        },
      ]
    }
    if (form.value.type === 5) {
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'order',
          children: [
            {
              first: '短租：还车时间前',
              value: form.value.sendConfigJson.soTimeDelta,
              unit: '分钟',
              precision: 0,
              second: '还未还车则通知',
            },
          ],
        },
        {
          type: 'select',
          ident: 'order',
          children: [
            {
              first: '长租：每天',
              value: form.value.sendConfigJson.loDayHour,
              second: '通知当天还车但未还的订单',
            },
          ],
        },
      ]
    }
    if (form.value.type === 6) {
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'order',
          children: [
            {
              first: '短租：交车时间',
              value: form.value.sendConfigJson.soTimeDelta,
              unit: '分钟',
              precision: 0,
              second: '后未交车则通知',
            },
          ],
        },
        {
          type: 'select',
          ident: 'order',
          children: [
            {
              first: '长租：每天',
              value: form.value.sendConfigJson.loDayHour,
              second: '通知昨天交车但未交的订单',
            },
          ],
        },
      ]
    }
    if (form.value.type === 7) {
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'order',
          children: [
            {
              first: '短租：还车时间',
              value: form.value.sendConfigJson.soTimeDelta,
              unit: '分钟',
              precision: 0,
              second: '后还未还车则通知',
            },
          ],
        },
        {
          type: 'select',
          ident: 'order',
          children: [
            {
              first: '长租：每天',
              value: form.value.sendConfigJson.loDayHour,
              second: '通知昨天还车但未还的订单',
            },
          ],
        },
      ]
    }
    if (
      form.value.type === 8 ||
      form.value.type === 11 ||
      form.value.type === 12 ||
      form.value.type === 13 ||
      form.value.type === 14 ||
      form.value.type === 15 ||
      form.value.type === 16 ||
      form.value.type === 19
    ) {
      noticeDialogData.value = [
        {
          type: 'select',
          ident: 'hour',
          children: [
            {
              first: '每天',
              value: form.value.sendConfigJson.dayHour,
              second: '集中发送',
            },
          ],
        },
      ]
    }
    if (form.value.type === 9) {
      noticeDialogTitle.value = '设置提醒金额'
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'price',
          children: [
            {
              first: '账户余额低于',
              value: form.value.sendConfigJson.amount,
              precision: 2,
              unit: '元',
              second: '立即提醒',
            },
          ],
        },
      ]
    }
    if (form.value.type === 17 || form.value.type === 18) {
      layout.value = 'horizontal'
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'car',
          children: [
            {
              first: form.value.type === 17 ? '车辆待维修时间超过' : '车辆待处理违章时间超过',
              value: form.value.sendConfigJson.timeDelta,
              precision: 0,
              slotName: 'append',
            },
          ],
        },
        {
          type: 'select',
          ident: 'car',
          children: [
            {
              first: '每天',
              value: form.value.sendConfigJson.dayHour,
              second: '集中发送',
            },
          ],
        },
      ]
    }
    if (form.value.type === 20) {
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'order',
          children: [
            {
              first: '短租：工单预计完成前',
              value: form.value.sendConfigJson.soTimeDelta,
              unit: '分钟',
              precision: 0,
              second: '未指派负责人则通知车管家',
            },
          ],
        },
        {
          type: 'select',
          ident: 'order',
          children: [
            {
              first: '长租：每天',
              value: form.value.sendConfigJson.loDayHour,
              second: '通知车管家，工单预计当天完成但未指派负责人',
            },
          ],
        },
      ]
    }
    if (form.value.type === 24) {
      noticeDialogData.value = [
        {
          type: 'input',
          ident: 'order',
          children: [
            {
              first: '短租：工单预计完成前',
              value: form.value.sendConfigJson.soTimeDelta,
              unit: '分钟',
              precision: 0,
              second: '且工单状态为待开始，则通知负责人',
            },
          ],
        },
        {
          type: 'select',
          ident: 'order',
          children: [
            {
              first: '长租：工单预计当天完成但未操作，则每天',
              value: form.value.sendConfigJson.loDayHour,
              second: '通知负责人',
            },
          ],
        },
      ]
    }
  }

  const onCloseOrderTime = () => {
    form.value.sendConfigJson = cloneFormValue.value.sendConfigJson
  }

  /**
   * 获取推送员工数据
   * @param value 搜索关键字
   */
  const getRoleData = (value?: string) => {
    return new Promise((resolve) => {
      getStaff({ keyword: value }).then((res: any) => {
        const result = res.result
        let roleData = []
        roleData = result.map((item: any) => {
          return {
            label: item.namePhone,
            value: item.id + '',
          }
        })
        resolve(roleData)
      })
    })
  }

  const sendTargetSource = ref() // 1-角色 2-岗位 3-员工
  const onChange = (value: string | number | boolean) => {
    const sendTarget = form.value.sendTargetTypeSelectList.find((item: any) => item.value === value + '')
    sendTargetSource.value = sendTarget.dataSource
  }

  const replaceObject = (arr1: any[], arr2: any[]) => {
    console.log(arr1, arr2, 'arr1, arr2')

    if (arr1.length === 0 && arr2.length === 0) {
      return []
    }

    for (let i = 0; i < arr1.length; i++) {
      const obj1 = arr1[i]

      const obj2 = arr2.find((item) => item.targetId == obj1.targetId)

      if (obj2) {
        arr1[i] = obj2
      }
    }

    return arr1
  }

  /**
   * 获取设置时间弹窗的标题
   * @param type 模板类型
   */
  const getSettingTimeTitle = (type: number) => {
    switch (type) {
      case 9:
        return '设置提醒金额'
      default:
        return '设置通知时间'
    }
  }

  const onOkOrderTime = (val: any) => {
    console.log(val, 'val')
    switch (val.type) {
      case 'order':
        form.value.sendConfigJson.soTimeDelta = val.value[0]
        form.value.sendConfigJson.loDayHour = val.value[1]
        break
      case 'hour':
        form.value.sendConfigJson.dayHour = val.value[0]
        break
      case 'price':
        form.value.sendConfigJson.amount = val.value[0]
        break
      case 'car':
        form.value.sendConfigJson.timeDelta = val.value[0]
        form.value.sendConfigJson.dayHour = val.value[1]
        break
    }
    onPushTime()
  }

  // 修改推送时间
  const onPushTime = () => {
    changePushTime({ type: form.value.type, sendConfigJson: form.value.sendConfigJson }).then((res: any) => {
      form.value.sendTimeDesc = res.result
      visible.value = false
    })
  }

  const selectedList = ref<any>([])
  const sendTargetObj = ref<any>({}) // 记录选择的推送人员
  const cloneFormValue = ref<any>()
  /**
   * 获取模版详情
   * @param id 模版id
   */
  const getBusinessMessageDetailData = (id: string | string[]) => {
    getBusinessMessageDetail({ id }).then((res: any) => {
      form.value = res.result
      cloneFormValue.value = cloneDeep(res.result)
      form.value.memo = res.result.memo.split('\r\n')
      settingButton.value = getSettingTimeTitle(form.value.type)

      // 根据 sendTargetType 获取推送人员类型
      // dataSource: 1-角色 2-岗位 3-员工
      const sendTarget = form.value.sendTargetTypeSelectList.find((item: any) => item.value === form.value.sendTargetType + '')
      sendTargetSource.value = sendTarget.dataSource

      if (sendTarget.dataSource) {
        sendTargetObj.value = {
          [sendTarget.dataSource]: form.value.sendTargetList.map((item: any) => item.targetId + ''),
        }
      }

      selectedList.value = []
      console.log(form.value, sendTargetObj.value, sendTarget.dataSource, 'form.value getBusinessMessageDetailData')
    })
  }

  const onClickView = (type: string) => {
    viewType.value = type
    viewVisible.value = true
  }

  const allRoleList = ref<any>([]) // 所有角色数据
  const getRoleList = () => {
    getEpList().then((res: any) => {
      allRoleList.value = res.result
    })
  }

  const allPostList = ref<any>([]) // 所有岗位数据
  const getPostList = () => {
    getSysParams({ codeList: ['staff_post'] }).then((res: any) => {
      allPostList.value = res.result.staff_post
    })
  }

  onMounted(() => {
    if (route.params.id) {
      getRoleList()
      getPostList()
      getBusinessMessageDetailData(route.params.id)
    }
  })

  const submitFn = () => {
    formRef.value.validate((error: any) => {
      if (error) {
        return
      }
      if (
        (sendTargetSource.value == 1 || sendTargetSource.value == 2 || sendTargetSource.value == 3) &&
        !sendTargetObj.value[sendTargetSource.value]?.length
      ) {
        Message.error('请选择推送人员')
        return
      }

      // 将数据转换成后端需要的格式
      const data = (sendTargetObj.value[sendTargetSource.value] ?? []).map((item: any) => ({ targetId: item }))
      const result = replaceObject(data, form.value.sendTargetList)
      form.value.sendTargetList = result
      console.log(form.value, 'form.value')

      okLoading.value = true
      saveBusinessMessage(form.value)
        .then((res: any) => {
          console.log(res, 'res')
          navigateBack()
          okLoading.value = false
        })
        .catch((error: any) => {
          console.log(error, 'error')
          Message.error(error.message)
          okLoading.value = false
        })
    })
  }
</script>

<style lang="less" scoped>
  :deep(.arco-form-item) {
    margin-bottom: 0;
  }
  :deep(.page-form-item-label) {
    justify-content: left;
  }
  .page-container {
    .descriptions {
      font-size: 14px;
      font-weight: 400;

      .descriptions-title {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 16px;
      }
      .descriptions-item {
        width: 100%;
        display: flex;
        margin-bottom: 8px;
        color: #1d2129;

        .label {
          color: #4e5969;
          margin-right: 8px;
          text-align: right;
          min-width: 90px;
          &:after {
            content: '：';
          }
        }
      }
    }
    .message-center-box {
      padding: 20px 20px;
      background: rgba(247, 248, 250, 0.5);
      margin-bottom: 20px;
      &:last-child {
        margin-bottom: 0;
      }
      .message-center-title {
        font-size: 14px;
        font-weight: 600;
        color: #1d2129;
        margin-bottom: 6px;
      }
      .message-center-item {
        display: flex;
        padding: 16px 16px;
        border-radius: 2px 2px 2px 2px;
        border: 1px solid #e5e8ef;
        margin-bottom: 20px;
        &:last-child {
          margin-bottom: 0;
        }
      }
      .text {
        flex-direction: column;
        font-size: 14px;
        font-weight: 400;
        color: #1d2129;
        .text-title {
          margin-bottom: 8px;
        }
        .text-content {
          margin-right: 10px;
        }
      }
    }
  }
</style>
